﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using PhilWicklund.com.SiteCreationWorkflow.Data;

namespace PhilWicklund.com.SiteCreationWorkflow.Utilities
{
	public enum ApprovalWorkflowStatus
	{
		Null,
		New,
		NotApproved,
		Approved
	}; 

	public static class WorkFlowStatusService
	{
		static string key = PropertyBagKeys.SiteCreationWorkflow.ToString();

		public static void SetWorkflowStatus(string webUrl, ApprovalWorkflowStatus status)
		{
			SPSecurity.RunWithElevatedPrivileges(delegate() 
			{
				using (SPSite site = new SPSite(webUrl))
				{
					string relativeWebUrl = "";
					if (site.Url != webUrl) // NOT Root Web
						relativeWebUrl = webUrl.Substring(site.Url.Length + 1);
					using (SPWeb web = site.OpenWeb(relativeWebUrl))
					{
						web.AllowUnsafeUpdates = true;
						if (web.Properties.ContainsKey(key) == true)
						{
							web.Properties[key] = status.ToString();
							web.Properties.Update();
						}
						else
						{
							web.Properties.Add(key, status.ToString());
							web.Properties.Update();
						}
						web.AllowUnsafeUpdates = false;
					}
				}
			});
		}

		public static ApprovalWorkflowStatus GetWorkflowStatus(string webUrl)
		{
			ApprovalWorkflowStatus status = ApprovalWorkflowStatus.Null;
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite site = new SPSite(webUrl))
				{
					string relativeWebUrl = "";
					if (site.Url != webUrl) // NOT Root Web
						relativeWebUrl = webUrl.Substring(site.Url.Length + 1);
					using (SPWeb web = site.OpenWeb(relativeWebUrl))
					{

						if (web.Properties.ContainsKey(key) == true)
						{
							status = (ApprovalWorkflowStatus)Enum.Parse(typeof(ApprovalWorkflowStatus), web.Properties[key]);
						}
						else
						{
							status = ApprovalWorkflowStatus.Null;
						}
					}
				}
			});
			return status;
		}
	}
}
